from django import forms
from web.models import Goods_Category, Goods_Category_Sub, Product, Goods_Image
from django.http import JsonResponse
from web.apis import tools
from django.forms.models import model_to_dict
from django.views.decorators.csrf import csrf_exempt

# 商品主分类表单
class CategoryForm(forms.ModelForm):
    class Meta:
        model = Goods_Category
        fields = "__all__"

    def clean_name(self):
        name = self.cleaned_data.get('name')
        if not name:
            raise forms.ValidationError("分类名称不能为空")
        if len(name) > 10:
            raise forms.ValidationError("分类名称不能超过10个字符")
        return name

# 商品次分类表单
class CategorySubForm(forms.ModelForm):
    class Meta:
        model = Goods_Category_Sub
        fields = "__all__"

    def clean_name(self):
        name = self.cleaned_data.get('name')
        if not name:
            raise forms.ValidationError("次分类名称不能为空")
        if len(name) > 10:
            raise forms.ValidationError("次分类名称不能超过10个字符")
        return name

# 创建主分类
@csrf_exempt
def create_category(request):
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                category = form.instance
                category_dict = model_to_dict(category)
                category_dict['create_time'] = category.create_time.strftime('%Y-%m-%d %H:%M:%S')
                category_dict['update_time'] = category.update_time.strftime('%Y-%m-%d %H:%M:%S')
                return JsonResponse(tools.ReturnData(code=200, msg='创建分类成功', data=category_dict))
            except Exception as e:
                return JsonResponse(tools.ReturnData(code=400, msg=f'创建分类失败: {str(e)}'))
        else:
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=400, msg=f' {error_msg}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 创建次分类
@csrf_exempt
def create_category_sub(request):
    if request.method == 'POST':
        form = CategorySubForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                category_sub = form.instance
                category_sub_dict = model_to_dict(category_sub)
                category_sub_dict['create_time'] = category_sub.create_time.strftime('%Y-%m-%d %H:%M:%S')
                category_sub_dict['update_time'] = category_sub.update_time.strftime('%Y-%m-%d %H:%M:%S')
                return JsonResponse(tools.ReturnData(code=200, msg='创建次分类成功', data=category_sub_dict))
            except Exception as e:
                return JsonResponse(tools.ReturnData(code=400, msg=f'创建次分类失败: {str(e)}'))
        else:
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=400, msg=f' {error_msg}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 获取主分类列表
@csrf_exempt
def get_category_list(request):
    if request.method == 'GET':
        try:
            categories = Goods_Category.objects.all()
            category_list = []
            for category in categories:
                category_dict = model_to_dict(category)
                category_dict['create_time'] = category.create_time.strftime('%Y-%m-%d %H:%M:%S')
                category_dict['update_time'] = category.update_time.strftime('%Y-%m-%d %H:%M:%S')
                category_list.append(category_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='获取分类列表成功', data=category_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取分类列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 获取次分类列表
@csrf_exempt
def get_category_sub_list(request):
    if request.method == 'GET':
        try:
            category_subs = Goods_Category_Sub.objects.all()
            category_sub_list = []
            for category_sub in category_subs:
                category_sub_dict = model_to_dict(category_sub)
                category_sub_dict['create_time'] = category_sub.create_time.strftime('%Y-%m-%d %H:%M:%S')
                category_sub_dict['update_time'] = category_sub.update_time.strftime('%Y-%m-%d %H:%M:%S')
                category_sub_list.append(category_sub_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='获取次分类列表成功', data=category_sub_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取次分类列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 获取单个主分类
@csrf_exempt
def get_category(request, category_id):
    if request.method == 'GET':
        try:
            category = Goods_Category.objects.filter(id=category_id).first()
            if not category:
                return JsonResponse(tools.ReturnData(code=400, msg='分类不存在'))
            
            category_dict = model_to_dict(category)
            category_dict['create_time'] = category.create_time.strftime('%Y-%m-%d %H:%M:%S')
            category_dict['update_time'] = category.update_time.strftime('%Y-%m-%d %H:%M:%S')
            return JsonResponse(tools.ReturnData(code=200, msg='获取分类信息成功', data=category_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取分类信息失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 获取单个次分类
@csrf_exempt
def get_category_sub(request, category_sub_id):
    if request.method == 'GET':
        try:
            category_sub = Goods_Category_Sub.objects.filter(id=category_sub_id).first()
            if not category_sub:
                return JsonResponse(tools.ReturnData(code=400, msg='次分类不存在'))
            
            category_sub_dict = model_to_dict(category_sub)
            category_sub_dict['create_time'] = category_sub.create_time.strftime('%Y-%m-%d %H:%M:%S')
            category_sub_dict['update_time'] = category_sub.update_time.strftime('%Y-%m-%d %H:%M:%S')
            return JsonResponse(tools.ReturnData(code=200, msg='获取次分类信息成功', data=category_sub_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取次分类信息失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 更新主分类
@csrf_exempt
def update_category(request, category_id):
    if request.method == 'POST':
        try:
            category = Goods_Category.objects.filter(id=category_id).first()
            if not category:
                return JsonResponse(tools.ReturnData(code=400, msg='分类不存在'))
            
            form = CategoryForm(request.POST, instance=category)
            if form.is_valid():
                form.save()
                category_dict = model_to_dict(form.instance)
                category_dict['create_time'] = form.instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
                category_dict['update_time'] = form.instance.update_time.strftime('%Y-%m-%d %H:%M:%S')
                return JsonResponse(tools.ReturnData(code=200, msg='更新分类成功', data=category_dict))
            else:
                error_msg = tools.get_first_error(form)
                return JsonResponse(tools.ReturnData(code=400, msg=f' {error_msg}'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'更新分类失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用PUT方法'))

# 更新次分类
@csrf_exempt
def update_category_sub(request, category_sub_id):
    if request.method == 'POST':
        try:
            category_sub = Goods_Category_Sub.objects.filter(id=category_sub_id).first()
            if not category_sub:
                return JsonResponse(tools.ReturnData(code=400, msg='次分类不存在'))
            
            form = CategorySubForm(request.POST, instance=category_sub)
            if form.is_valid():
                form.save()
                category_sub_dict = model_to_dict(form.instance)
                category_sub_dict['create_time'] = form.instance.create_time.strftime('%Y-%m-%d %H:%M:%S')
                category_sub_dict['update_time'] = form.instance.update_time.strftime('%Y-%m-%d %H:%M:%S')
                return JsonResponse(tools.ReturnData(code=200, msg='更新次分类成功', data=category_sub_dict))
            else:
                error_msg = tools.get_first_error(form)
                return JsonResponse(tools.ReturnData(code=400, msg=f' {error_msg}'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'更新次分类失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用PUT方法'))

# 删除主分类
@csrf_exempt
def delete_category(request, category_id):
    if request.method == 'DELETE':
        try:
            category = Goods_Category.objects.filter(id=category_id).first()
            if not category:
                return JsonResponse(tools.ReturnData(code=400, msg='分类不存在'))
            
            category.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除分类成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除分类失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))

# 删除次分类
@csrf_exempt
def delete_category_sub(request, category_sub_id):
    if request.method == 'DELETE':
        try:
            category_sub = Goods_Category_Sub.objects.filter(id=category_sub_id).first()
            if not category_sub:
                return JsonResponse(tools.ReturnData(code=400, msg='次分类不存在'))
            
            category_sub.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除次分类成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除次分类失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))

# 根据主分类ID获取次分类列表
@csrf_exempt
def get_category_subs_by_parent(request, parent_id):
    if request.method == 'GET':
        try:
            # 先检查主分类是否存在
            parent_category = Goods_Category.objects.filter(id=parent_id).first()
            if not parent_category:
                return JsonResponse(tools.ReturnData(code=400, msg='主分类不存在'))
            
            # 获取该主分类下的所有次分类
            category_subs = Goods_Category_Sub.objects.filter(parent_id=parent_id)
            category_sub_list = []
            for category_sub in category_subs:
                category_sub_dict = model_to_dict(category_sub)
                category_sub_dict['create_time'] = category_sub.create_time.strftime('%Y-%m-%d %H:%M:%S')
                category_sub_dict['update_time'] = category_sub.update_time.strftime('%Y-%m-%d %H:%M:%S')
                category_sub_list.append(category_sub_dict)
            
            return JsonResponse(tools.ReturnData(
                code=200, 
                msg='获取主分类下的次分类列表成功', 
                data={
                    'parent_category': model_to_dict(parent_category),
                    'sub_categories': category_sub_list
                }
            ))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取次分类列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))

# 根据分类ID获取该分类下的全部商品
@csrf_exempt
def get_products_by_category(request, category_id):
    if request.method == 'GET':
        try:
            if str(category_id) == '0':
                # 获取全部商品
                products = Product.objects.all()
                
            else:
                # 查询主分类下的商品
                products_main = Product.objects.filter(category_id=category_id)
                
                # 查询次分类下的商品
                products_sub = Product.objects.filter(category_sub_id=category_id)
                
                # 在category_sub中查询
                # 获取当前分类下的所有次分类
                category_sub = Goods_Category_Sub.objects.filter(parent_id=category_id)
                
                # 遍历每个次分类，获取其下的所有商品
                for sub in category_sub:
                    products_sub = Product.objects.filter(category_sub_id=sub.id)
                    
                    # 将当前次分类下的商品转换为列表
                    products_sub_list = list(products_sub)
                    unique_products_sub = []
                    for p in products_sub_list:
                        if p not in products_main:
                            unique_products_sub.append(p)
                    
                    # 将当前次分类下的唯一商品添加到主分类下的商品列表中
                    products_main = list(products_main)
                    products_main.extend(unique_products_sub)

                # 合并去重
                products = list(products_main) + [p for p in products_sub if p not in products_main]
            product_list = []
            for product in products:
                product_dict = model_to_dict(product)
                # 如果该商品的分类是下架，则不显示
                if product.category:
                    if product.category.status != 1:
                        continue
                if product.category_sub:
                    if product.category_sub.status != 1:
                        continue
                product_dict['image'] = []
                # 获取商品图片
                product_image = Goods_Image.objects.filter(product_id=product.id)
                for image in product_image:
                    image_dict = model_to_dict(image)
                    image_dict['create_time'] = image.create_time.strftime('%Y-%m-%d %H:%M:%S')
                    image_dict['update_time'] = image.update_time.strftime('%Y-%m-%d %H:%M:%S')
                    image_dict['image'] = image.image.url
                    product_dict['image'].append(image_dict)
                product_dict['create_time'] = product.create_time.strftime('%Y-%m-%d %H:%M:%S')
                product_dict['update_time'] = product.update_time.strftime('%Y-%m-%d %H:%M:%S')
                product_list.append(product_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='获取分类下商品成功', data=product_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取分类下商品失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用GET方法'))
